#!/usr/bin/env python

import argparse
import sys
import os
from configparser import RawConfigParser, NoSectionError, ParsingError

_file = os.path.join(os.environ['HOME'], '.boxes')

parser = argparse.ArgumentParser(description='SSH to a remote box via an alias')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
parser.add_argument('box', metavar='BOX', type=str, nargs=1, help='Named alias located in ~/.boxes')

args = parser.parse_args()

def exit_print(statement, exit_code):
    print('ss: {}. Aborting.'.format(statement), file=sys.stderr)
    sys.exit(exit_code)

def create_default():
    print('No .boxes file found in your home directory.')
    print('Creating default... be sure to edit it before use!')
    with open(_file, 'w') as f:
        f.write('[boxes]\n')
        for i in range(5):
            f.write('alias_{}=login@domain.com\n'.format(i))

def get_box(cmd):
    config = RawConfigParser()
    config.read(_file)

    boxes = config.items('boxes')
    b_map = dict()

    for box, account in boxes:
        b_map[box] = account

    return b_map.get(cmd)

if not os.path.exists(_file):
    create_default()
    exit_print('Edit your ~/.boxes file before using', 1)

cmd = sys.argv[1]

try:
    box = get_box(cmd)
except (NoSectionError, ParsingError) as e:
    exit_print('Malformed .boxes file', 2)

if not box:
    exit_print('Unknown box', 3)
    sys.exit(3)

print('Connecting to {}...'.format(box))
os.system('ssh {}'.format(box))
